package com.gl.handler;

import com.alibaba.fastjson.JSON;
import com.gl.common.utils.Result;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

/**
 * Created by GAOL on 2017/5/12.
 * 替换springboot 默认的BasicErrorController重新定向错误页面
 */
@Controller
public class CustomErrorController implements ErrorController {

    private static Logger logger = LoggerFactory.getLogger(CustomErrorController.class);

    @Value("${error.path:/error}")
    private String errorPath;

    /**
     * 自定义返回信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "${error.path:/error}")
    @ResponseBody
    public Result handleError(HttpServletRequest request) {
        Map<String, Object> attributes = getErrorAttributes(request);
        int code = (int) attributes.get("status");
        String message = (String) attributes.get("error");
        logError(attributes, request);
        return new Result(code, message);
    }


    /**
     * 获取错误信息
     *
     * @param request
     * @return
     */
    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        ErrorAttributes errorAttributes = new DefaultErrorAttributes();
        return errorAttributes.getErrorAttributes(requestAttributes, false);
    }


    private void logError(Map<String, Object> attributes, HttpServletRequest request) {
        logger.info("**************************Request Error**************************");
        logger.error("Error request address：{}", request.getRemoteAddr());
        logger.error("User：{}", request.getRemoteUser());
        logger.error("Info：{}", JSON.toJSONString(attributes));
    }

    @Override
    public String getErrorPath() {
        return errorPath;
    }
}
